package com.example.goodsmanagementcabinet.activity;

import android.app.Dialog;
import android.content.Context;
import android.os.CountDownTimer;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.example.goodsmanagementcabinet.R;
import com.example.goodsmanagementcabinet.adapter.CheckKeyAdapter;
import com.example.goodsmanagementcabinet.adapter.KeyAdapter;
import com.example.goodsmanagementcabinet.adapter.KeyUserAdapter;
import com.example.goodsmanagementcabinet.adapter.UserListAdapter;
import com.example.goodsmanagementcabinet.base.BaseActivity;
import com.example.goodsmanagementcabinet.base.GoodBoxManagerApp_;
import com.example.goodsmanagementcabinet.bean.KeyBean;
import com.example.goodsmanagementcabinet.bean.UserBean;
import com.example.goodsmanagementcabinet.db.DatabaseManager;
import com.example.goodsmanagementcabinet.otto.OttoMsg;
import com.example.goodsmanagementcabinet.serialport.SerialPortConnect;
import com.example.goodsmanagementcabinet.utils.Utils;
import com.squareup.otto.Subscribe;

import org.androidannotations.annotations.AfterViews;
import org.androidannotations.annotations.Background;
import org.androidannotations.annotations.EActivity;
import org.androidannotations.annotations.Fullscreen;
import org.androidannotations.annotations.UiThread;
import org.androidannotations.annotations.ViewById;

import java.util.ArrayList;
import java.util.List;

@Fullscreen
@EActivity(R.layout.admin_operating_fragment)
public class AdminGoodManager extends BaseActivity implements View.OnClickListener {

    @ViewById
    GridView keyGridVew;
    @ViewById
    LinearLayout btnNewKey, btnDeleteKey, btnKeyUser;
    @ViewById
    ImageView toHome;
    KeyAdapter keyAdapter;
    KeyBean newKey;
    long outTime;
    CountDownTimer timer;
    boolean isFinish = false;
    List<KeyBean> keyBeanList = new ArrayList<>();
    Dialog dialog, keyInfoDialog;
    TextView textView, mKeyCodeTv;
    Dialog adddialog;
    Context context;
    private KeyUserAdapter keyUserAdapter;
    private ListView mUserGv;
    List<UserBean> userList = new ArrayList<>();
    List<UserBean> bindList = new ArrayList<>();
    List<UserBean> unbindList = new ArrayList<>();
    private int doingType;
    boolean success = false;

    @AfterViews
    public void afterViews() {
        context = this;
        btnNewKey.setOnClickListener(this);
        btnDeleteKey.setOnClickListener(this);
        btnKeyUser.setOnClickListener(this);
        toHome.setOnClickListener(this);
        keyAdapter = new KeyAdapter(this);
        keyGridVew.setAdapter(keyAdapter);
        keyGridVew.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                keyAdapter.changeState(i);
            }
        });
        updateUI();
    }

    @UiThread
    public void updateUI() {
        keyBeanList = DatabaseManager.getInstance(GoodBoxManagerApp_.getInstance()).queryAllKey();
        keyAdapter.changeState(keyBeanList.size() + 1);
        keyAdapter.notifyRefresh(keyBeanList);
    }

    @Subscribe
    @Background
    public void handlerOtto(OttoMsg msg) {
        if (TextUtils.equals(OttoMsg.OTTO_CHECK_KEYS, msg.which)) {
            newKey = (KeyBean) msg.data;
        } else if (TextUtils.equals(msg.which, OttoMsg.OTTO_BIND_USER)) {
            UserBean object = (UserBean) msg.data;
            if (doingType == 1) {
                //当前为物品绑定
                if (object instanceof UserBean) {
                    DatabaseManager.getInstance(GoodBoxManagerApp_.getInstance()).insertToKeyUser(object.getUserId(), newKey.getKeyId());
                    unbindList.remove(object);
                    bindList.add(object);
                }
            } else {
                //当前为物品解绑
                if (object instanceof UserBean) {
                    DatabaseManager.getInstance(GoodBoxManagerApp_.getInstance()).deleteKeyUserByKeyidAndUserId(object.getUserId(), newKey.getKeyId());
                    bindList.remove(object);
                    unbindList.add(object);
                }
            }
            userList.remove(object);
            updateDialogList();
        }
    }

    @UiThread
    void updateDialogList() {
        if (doingType == 1) {
            keyUserAdapter.notifyRefresh(unbindList);
        } else {
            keyUserAdapter.notifyRefresh(bindList);
        }
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.btnNewKey:
                if (newKey == null) {
                    speak("请选择钥匙位");
                } else {
                    if (TextUtils.isEmpty(newKey.getKeyId())) {
                        KeyInfoDialog(newKey);
                    } else {
                        speak("此位置已存在钥匙");
                    }
                }
                break;
            case R.id.btnDeleteKey:
                if (newKey == null) {
                    speak("请选择钥匙");
                } else {
                    if (TextUtils.isEmpty(newKey.getKeyId())) {
                        speak("此位置没有钥匙");
                        return;
                    }
                    if (newKey.getStatus().equals("1")) {
                        deleteDialog(newKey);
                    } else {
                        speak("请选择在位的钥匙");
                    }
                }
                break;
            case R.id.btnKeyUser:
                if (newKey != null) {
                    if (TextUtils.isEmpty(newKey.getKeyId())) {
                        speak("此位置没有钥匙，请选择正确的钥匙");
                        return;
                    }
                    getAllUser();
                }
                break;
            case R.id.toHome:
                finish();
                break;
        }
    }

    @Background
    public void getAllUser() {
        userList = DatabaseManager.getInstance(GoodBoxManagerApp_.getInstance()).queryUsers();
        bindList = DatabaseManager.getInstance(GoodBoxManagerApp_.getInstance()).queryUserByKeyId(newKey.getKeyId());
        if (userList.size() > 0) {
            if (bindList.size() > 0) {
                unbindList = userList;
                for (UserBean user : bindList) {
                    for (int a = unbindList.size() - 1; a >= 0; a--) {
                        if (TextUtils.equals(unbindList.get(a).getUserId(), user.getUserId())) {
                            unbindList.remove(unbindList.get(a));
                            break;
                        }
                    }
                }
            } else {
                unbindList = userList;
            }
        }
        showBindDialog();
    }

    private void KeyInfoDialog(final KeyBean key) {
        if (keyInfoDialog == null) {
            keyInfoDialog = new Dialog(this, R.style.add_dialog);
            keyInfoDialog.setContentView(R.layout.item_new_keyinfo);
            keyInfoDialog.setCancelable(false);
            WindowManager.LayoutParams layoutParams = keyInfoDialog.getWindow().getAttributes();
            keyInfoDialog.getWindow().setAttributes(layoutParams);
            Window dialogWindow = keyInfoDialog.getWindow();
            dialogWindow.setGravity(Gravity.CENTER);
            final EditText mNameTv, mInfoTv;
            mNameTv = keyInfoDialog.findViewById(R.id.mNameTv);
            mInfoTv = keyInfoDialog.findViewById(R.id.mInfoTv);
            mKeyCodeTv = keyInfoDialog.findViewById(R.id.mKeyCodeTv);
            Button closebtn = keyInfoDialog.findViewById(R.id.mCancel);
            closebtn.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    isFinish = false;
                    if (timer != null) {
                        timer.cancel();
                    }
                    newKey = null;
                    updateUI();
                    keyInfoDialog.dismiss();
                    success = false;
                }
            });

            Button submit = keyInfoDialog.findViewById(R.id.mSubmit);
            submit.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    String mKeyName = mNameTv.getText().toString().trim();
                    String mKeyNo = mInfoTv.getText().toString().trim();
                    String mlocation = key.getLocation();
                    if (TextUtils.isEmpty(mKeyName) || TextUtils.isEmpty(mKeyNo) || TextUtils.isEmpty(mlocation)) {
                        speak("内容不完整");
                    } else {
                        outTime = System.currentTimeMillis();
                        newKey.setKeyId(mKeyNo);
                        newKey.setKeyName(mKeyName);
                        newKey.setLocation(mlocation);
                        newKey.setStatus("1");
                        mlock();

                    }
                }
            });
        }
        keyInfoDialog.show();
    }

    public void mlock() {
        SerialPortConnect.getInstance().readCode(Integer.parseInt(newKey.getLocation()));
        System.out.println("XXXXXXXXXXXx:" + (System.currentTimeMillis() - outTime));
        if (System.currentTimeMillis() - outTime > 60 * 1000) {
            isFinish = false;
            if (timer != null) {
                timer.cancel();
            }
            speak("操作超时");
            newKey = null;
            hidiDialog();
            updateUI();
            success = false;
            return;
        }
        if (isFinish) {
            if (timer != null) {
                timer.cancel();
            }
            newKey = null;
            speak("操作超时");
            hidiDialog();
            updateUI();
            success = false;
            return;
        }
        timer = new CountDownTimer(6000, 2000) {
            public void onTick(long millisUntilFinished) {
                String lockState = SerialPortConnect.getInstance().getlockState(Integer.parseInt(newKey.getLocation()) - 1);
                e("locstate = " + lockState);
                if (TextUtils.equals(lockState, "00") || TextUtils.equals(lockState, "01")) {
                    if (!success) {
                        SerialPortConnect.getInstance().openLock(Integer.parseInt(newKey.getLocation()));
                    } else {
                        String keycodes = SerialPortConnect.getInstance().getKeyCode(Integer.parseInt(newKey.getLocation()) - 1);
                        newKey.setKeyCode(keycodes);
                        DatabaseManager.getInstance(GoodBoxManagerApp_.getInstance()).insertToKey(newKey);
                        hidiDialog();
                        speak("操作成功");
                        outTime = System.currentTimeMillis();
                        timer.cancel();
                        newKey = null;
                        updateUI();
                    }
                } else if (TextUtils.equals(lockState, "03")) {
                    isFinish = false;
                    if (timer != null) {
                        timer.cancel();
                    }
                    speak("锁体损坏开锁失败");
                    hidiDialog();
                    updateUI();
                    success = false;
                    return;
                } else if (TextUtils.equals(lockState, "02")) {
                    if (success) {
                        speak("请关闭柜门");
                    }
                }
            }

            public void onFinish() {
                String keycodes = SerialPortConnect.getInstance().getKeyCode(Integer.parseInt(newKey.getLocation()) - 1);
                e("the keycode is " + keycodes);
                if (TextUtils.equals("00000000", keycodes) || TextUtils.isEmpty(keycodes) || TextUtils.equals(keycodes, "FFFFFFFF")) {
                    speak("请放入钥匙");
                    success = false;
                    mlock();
                } else {
                    success = true;
                    mlock();
                }
            }
        };
        timer.start();
    }

    @UiThread
    public void deleteDialog(final KeyBean key) {
        if (dialog == null) {
            dialog = new Dialog(this, R.style.add_dialog);
            dialog.setContentView(R.layout.item_pop_delete);
            dialog.setCancelable(false);
            Window dialogWindow = dialog.getWindow();
            dialogWindow.setGravity(Gravity.CENTER_HORIZONTAL);
            textView = dialog.findViewById(R.id.tv_user);
            Button affirmBtn = dialog.findViewById(R.id.accptBtn);
            Button mCancleBtn = dialog.findViewById(R.id.cancelBtn);
            //textView = dialog.findViewById(R.id.)
            affirmBtn.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    outTime = System.currentTimeMillis();
                    mlocks();
                }
            });

            mCancleBtn.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    isFinish = false;
                    if (timer != null) {
                        timer.cancel();
                    }
                    updateUI();
                    newKey = null;
                    success = false;
                    hidideleteDialog();
                }
            });
        }
        textView.setText("是否删除" + key.getKeyName());
        dialog.show();
    }

    public void mlocks() {
        SerialPortConnect.getInstance().readCode(Integer.parseInt(newKey.getLocation()));
        System.out.println("XXXXXXXXXXXx:" + (System.currentTimeMillis() - outTime));
        if (System.currentTimeMillis() - outTime > 60 * 1000) {
            isFinish = false;
            if (timer != null) {
                timer.cancel();
            }
            newKey = null;
            speak("操作超时");
            hidideleteDialog();
            updateUI();
            success = false;
            return;
        }
        if (isFinish) {
            if (timer != null) {
                timer.cancel();
            }
            newKey = null;
            speak("操作超时");
            hidideleteDialog();
            updateUI();
            success = false;
            return;
        }
        timer = new CountDownTimer(6000, 2000) {
            public void onTick(long millisUntilFinished) {
                String lockState = SerialPortConnect.getInstance().getlockState(Integer.parseInt(newKey.getLocation()) - 1);
                if (TextUtils.equals(lockState, "00") || TextUtils.equals(lockState, "01")) {
                    if (!success) {
                        SerialPortConnect.getInstance().openLock(Integer.parseInt(newKey.getLocation()));
                    } else {
                        DatabaseManager.getInstance(GoodBoxManagerApp_.getInstance()).deleteKeyByKeyId(newKey.getKeyId());
                        DatabaseManager.getInstance(GoodBoxManagerApp_.getInstance()).deleteKeyUserByKeyid(newKey.getKeyId());
                        speak("信息已删除");
                        newKey = null;
                        updateUI();
                        hidideleteDialog();
                        outTime = System.currentTimeMillis();
                        timer.cancel();
                        updateUI();
                        success = false;
                    }
                } else if (TextUtils.equals(lockState, "03")) {
                    isFinish = false;
                    if (timer != null) {
                        timer.cancel();
                    }
                    speak("锁位损坏开锁失败");
                    hidiDialog();
                    updateUI();
                    success = false;
                    return;
                } else if (TextUtils.equals(lockState, "02")) {
                    if (success) {
                        speak("请关闭柜门");
                    }
                }
            }

            public void onFinish() {
                e("the keycode is " + newKey.getLocation());
                String keycodes = SerialPortConnect.getInstance().getKeyCode(Integer.parseInt(newKey.getLocation()) - 1);
                e("the keycode is " + keycodes);
                if (!TextUtils.equals("00000000", keycodes)) {
                    success = false;
                    speak("请取走钥匙");
                    mlocks();
                } else {
                    success = true;
                    mlocks();
                }
            }
        };
        timer.start();
    }

    @UiThread
    public void hidiDialog() {
        keyInfoDialog.dismiss();
    }

    @UiThread
    public void hidideleteDialog() {
        dialog.dismiss();
    }

    TextView doingType_tv;

    @UiThread
    public void showBindDialog() {
        if (adddialog == null) {
            adddialog = new Dialog(context, R.style.add_dialog);
            adddialog.setContentView(R.layout.keyuser_add_list);
            adddialog.setCancelable(true);
            mUserGv = (ListView) adddialog.findViewById(R.id.addlist);
            keyUserAdapter = new KeyUserAdapter(context);
            mUserGv.setAdapter(keyUserAdapter);
            keyUserAdapter.notifyRefresh(userList);
            LinearLayout affirmBtn = (LinearLayout) adddialog.findViewById(R.id.mAffirmBtn);
            doingType_tv = (TextView) adddialog.findViewById(R.id.doingType);
            affirmBtn.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    adddialog.dismiss();
                }
            });
            LinearLayout bindBtn = adddialog.findViewById(R.id.mBindUser);
            LinearLayout unbindBtn = adddialog.findViewById(R.id.mUnBindUser);
            bindBtn.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    doingType = 1;
                    doingType_tv.setText("人员绑定");
                    keyUserAdapter.notifyRefresh(unbindList);
                }
            });
            unbindBtn.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    doingType = 2;
                    doingType_tv.setText("人员解绑");
                    keyUserAdapter.notifyRefresh(bindList);
                }
            });
            Utils.hideVirtualKey(adddialog.getWindow().getDecorView());
        }
        keyUserAdapter.notifyRefresh(userList);
        adddialog.show();
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        isFinish = true;
        keyAdapter = null;
        newKey = null;
        timer = null;
        isFinish = false;
        keyBeanList.clear();
        keyBeanList = null;
        dialog = null;
        keyInfoDialog = null;
        unbindList.clear();
        userList.clear();
        bindList.clear();
    }
}
